package com.ctgu.server.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctgu.server.dao.constant.CacheKey;
import com.ctgu.server.dao.dto.GroupDto;
import com.ctgu.server.dao.dto.GroupUserDto;
import com.ctgu.server.dao.entity.Group;
import com.ctgu.server.dao.vo.GroupVo;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.service.GroupService;
import com.ctgu.server.service.GroupUserService;
import com.ctgu.server.utils.RandomBag.RandomType;
import com.ctgu.server.utils.RandomBag.RandomUtils;
import com.ctgu.server.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ctgu
 * @since 2023-05-17
 */
@RestController
@RequestMapping("/server/group")
@Api(tags = "组织操作接口" )
@CrossOrigin
@Slf4j
public class GroupController {
    @Autowired
    private GroupService groupService;
    @Autowired
    private CacheChannel cacheChannel;


    @GetMapping("/list")
    @ApiOperation(notes = "获取所有组织信息",value = "获取所有组织信息")
    public Result groupList(){
        List<Group> groupList = (List<Group>) cacheChannel.get(CacheKey.Group_Redis,"list").getValue();
        if(groupList==null){
            groupList=groupService.list();
            cacheChannel.set(CacheKey.Group_Redis,"list",groupList);
        }
        return ResultUtil.success(groupList);
    }

    @GetMapping("/userList")
    @ApiOperation(notes = "获取用户当前创建组织的数量",value = "获取用户组织数量")
    public int userList(@NotEmpty(message = "用户ID不能为空") @RequestParam String userId){
        LambdaQueryWrapper<Group> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Group::getUserId,userId);
        return groupService.count(lambdaQueryWrapper);
    }

    @GetMapping("/captcha")
    @ApiOperation(notes = "获取邀请码",value = "获取邀请码")
    public String getCaptcha(@RequestParam Long groupId){
        CacheObject cacheObject= cacheChannel.get(CacheKey.CAPTCHA, String.valueOf(groupId));

        if(cacheObject.getValue()!=null){
            return cacheObject.getValue().toString();
        }

        //生成验证码
//        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 8);
//        specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
//        String captcha=StringUtils.lowerCase(specCaptcha.text());
        String captcha= RandomUtils.getRandom(8, RandomType.NUM_AND_CHAR).toString();
        cacheChannel.set(CacheKey.CAPTCHA, String.valueOf(groupId), captcha);
        cacheChannel.set(CacheKey.GROUP_ID,captcha, groupId);
        return captcha;
    }

    /**
     *
     * @param captcha
     * @param userId
     * @return
     */
    @GetMapping("/parseCaptcha")
    @ApiOperation(notes = "效验邀请码",value = "效验邀请码")
    public Result checkCaptcha(@RequestParam String captcha,@RequestParam String userId){
       //查询缓存中是否存在验证码
        Object s= cacheChannel.get(CacheKey.GROUP_ID,captcha).getValue();
        if(s==null){
            return ResultUtil.error("邀请码不存在！");
        }
        //对参数进行处理

        return groupService.addGroupRole(userId,s.toString());
    }
    @DeleteMapping("/deleteCaptcha")
    @ApiOperation(notes = "销毁邀请码",value = "销毁邀请码")
    public Result deleteCaptcha(@RequestParam String captcha){
        //查询缓存中是否存在验证码
        Object s= cacheChannel.get(CacheKey.GROUP_ID,captcha).getValue();
        if(s==null){
            return ResultUtil.error("邀请码不存在！");
        }
        cacheChannel.evict(CacheKey.GROUP_ID,captcha);
        cacheChannel.evict(CacheKey.CAPTCHA,s.toString());
        return ResultUtil.success("验证码销毁成功！");
    }

    @GetMapping("/list/{id}")
    @ApiOperation(notes = "获取用户组织列表",value = "获取用户加入的组织列表")
    public List<GroupVo> getUserGroupList(@NotEmpty(message = "参数不能为空") @PathVariable String id){
        log.info("/server/group/list/"+id);
        return groupService.getUserList(id);
    }

    @GetMapping("/create")
    @ApiOperation(notes = "创建组织",value = "创建组织")
    public Result createGroup(@RequestParam String userId,@RequestParam String groupName ){
        if(userId==null||groupName==null){
            return ResultUtil.error("参数错误");
        }
        return groupService.createGroup(userId,groupName);
    }

    @DeleteMapping("/delete")
    @ApiOperation(notes = "退出组织",value = "用户退出组织")
    public Result deleteGroupUser(@Validated @RequestBody GroupUserDto groupUserDto ){
//        if(userId==null||groupId==null){
//            return ResultUtil.error("参数错误");
//        }
        return groupService.deleteGroupUser(groupUserDto.getUserId(),groupUserDto.getGroupId());
    }
    @DeleteMapping("/deleteByAdmin")
    @ApiOperation(notes = "管理员踢人",value = "管理员移除用户")
    public Result deleteByAdmin(@Validated @RequestBody GroupUserDto groupUserDto){
        if(groupUserDto.getUserId()==null||groupUserDto.getGroupId()==null||groupUserDto.getOpId()==null){
            return ResultUtil.error("参数错误");
        }
//        else
//        if (groupUserDto.equals(opId)) {
//            return ResultUtil.error("管理员无法删除自己");
//        }
        return groupService.deleteByAdmin(groupUserDto.getUserId(),groupUserDto.getOpId(),groupUserDto.getGroupId());
    }

    @DeleteMapping("/deleteGroup")
    @ApiOperation(notes = "解散组织",value = "解散组织")
    public Result deleteGroupList( @RequestBody GroupUserDto groupUserDto ){
        if(groupUserDto.getUserId()==null||groupUserDto.getGroupId()==null){
            return ResultUtil.error("参数错误");
        }
        return groupService.deleteGroupList(groupUserDto.getUserId(),groupUserDto.getGroupId());
    }
    @PutMapping("/updateGroup")
    @ApiOperation(notes = "修改组织信息",value = "修改组织信息")
    public Result updateGroupInfo(@Validated  @RequestBody GroupDto groupDto){
        return groupService.updateGroupInfo(groupDto.getOpId(),groupDto);
    }
    @GetMapping("/getGroupInfo")
    @ApiOperation(notes = "获取组织信息",value = "获取组织信息")
    public Result updateGroupInfo(@RequestParam String groupId){
        if(groupId==null){
            return ResultUtil.error("组织Id不能为空");
        }
        //查询目标组织是否存在
        Group group= groupService.getById(groupId);
        if(group==null){
            return ResultUtil.error("未查询到目标组织");
        }
        return ResultUtil.success(group);
    }
    @GetMapping("/getGroupUser")
    @ApiOperation(notes = "获取成员信息",value = "获取成员信息")
    public Result getGroupUser(@RequestParam String groupId ){
        return groupService.getGroupUser(groupId);
    }
    @PutMapping("/updateGroupUser")
    @ApiOperation(notes = "修改成员信息",value = "修改成员信息")
    public Result updateGroupUser(@Validated @RequestBody GroupUserDto groupUserDto){
        return groupService.updateGroupUser(groupUserDto);
    }
}

